package com.mlt.back.web.servlet;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.mlt.back.beans.Brand;
import com.mlt.back.beans.Category;
import com.mlt.back.service.BrandService;
import com.mlt.back.service.CategoryService;
import com.mlt.back.service.impl.BrandServiceImpl;
import com.mlt.back.service.impl.CategoryServiceImpl;
import com.mlt.back.utils.DBUtil;
import com.mlt.back.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

@WebServlet({"/back/editBrand","/back/selectById","/back/brand","/back/brandSelectByCategoryId","/back/brandDel","/back/changeStatus","/back/brandUpdate","/back/brandImgUpload"})
@MultipartConfig/*文件上传必须有此注解*/
public class BrandServlet extends HttpServlet {
    private BrandService brandService=new BrandServiceImpl();
    private Part part;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取请求的servlet路径
        String servletPath = request.getServletPath();//"/back/brand"

        /**
         * chan
         * 获取全部品牌对象
         */
        if ("/back/brand".equals(servletPath)){
            doSelect(request,response);
        }
        /**
         * chan
         * 根据商品类型查找品牌
         */
        if ("/back/brandSelectByCategoryId".equals(servletPath)){
            doSelectByCategoryId(request,response);
        }
        /**
         * chan
         * 删除品牌
         */
        if ("/back/brandDel".equals(servletPath)){
            doDel(request,response);
        }
        /**
         * 陈雪融
         * 品牌状态更新
         */
        if ("/back/changeStatus".equals(servletPath)){
            doChangeStatus(request,response);
        }

        /**
         * chan
         * 接收图片并返回给前端(不执行sql)
         */
        if ("/back/brandImgUpload".equals(servletPath)){
            doImgUpload(request,response);
        }

        /**
         * chan
         * 根据brand_id查询产品
         */
        if ("/back/selectById".equals(servletPath)){
            doSelectById(request,response);
        }
        /**
         * chan
         * 修改品牌
         */
        if ("/back/editBrand".equals(servletPath)){
            doEditBrand(request,response);
        }
    }

    private void doEditBrand(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Brand brand = (Brand) session.getAttribute("brand");
        String brand_name = request.getParameter("brand_name");
        brand.setBrand_name(brand_name);
        String brand_desc = request.getParameter("brand_desc");
        brand.setBrand_desc(brand_desc);
        String brand_status = request.getParameter("brand_status");
        brand.setBrand_status(brand_status);
        Part part= request.getPart("brand_logo");
        if (part!=null&&part.getSize()>0) {
            //Content-Disposition是Part中的一个属性
            String header = part.getHeader("Content-Disposition");//form-data; name="brand_logo"; filename="2.jpeg"
            int index1 = header.lastIndexOf(".");
            int index2 = header.lastIndexOf("\"");
            String a = header.substring(index1, index2);//拿到文件的后缀名.jpeg
            //随机生成UUID，UUID里面有小横杆-，要替换为""，然后加上文件后缀名，组成新的文件名字
            String brand_logo = UUID.randomUUID().toString().replace("-", "") + a;
            //获取用于存放图片的文件夹真实路径
            String realPath = getServletContext().getRealPath("/upload");
            //存储图片，直接调用Part类的方法write(路径+文件名)
            part.write(realPath + "/" + brand_logo);
            //将图片路径存入对象，存相对路径
            brand.setBrand_logo("upload/" + brand_logo);
        }
        brandService.doUpdate(brand);
        response.sendRedirect(request.getContextPath()+"/brand_manage.html");
    }

    private void doSelectById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String brand_id = request.getParameter("brand_id");
        Brand brand=brandService.selectById(brand_id);
        HttpSession session = request.getSession();
        session.setAttribute("brand",brand);
    }

    private void doImgUpload(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //接收图片并保存图片
        Part brand_logo = request.getPart("brand_logo");
        //给图片重新命名
        String header = brand_logo.getHeader("Content-Disposition");
        int index1=header.lastIndexOf(".");
        int index2 = header.lastIndexOf("\"");
        String ext = header.substring(index1, index2);
        String imgName = UUID.randomUUID().toString().replace("-", "")+ext;
        //获取图片文件目录的路径（部署到服务器之后的路径）
        String realPath = getServletContext().getRealPath("/upload");
        //存储图片
        brand_logo.write(realPath+"/"+imgName);
        //返回文件的访问路径
        String path="/upload/"+imgName;
        ResultVO resultVO = new ResultVO(1000, path);
        String s = new Gson().toJson(resultVO);
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        System.out.println(s);
        out.print(s);
        out.flush();
        out.close();
    }

    /**
     * chan
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doChangeStatus(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String brand_id = request.getParameter("brand_id");
        String status = request.getParameter("status");
        brandService.changeStatus(brand_id,status);
    }

    /**
     * 陈雪融
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doSelect(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Brand> brandList=brandService.selectAll();
        //转换成json格式
        String s = JSON.toJSONString(brandList);
        //向前端打印
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(s);
    }

    /**
     * chan
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doDel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String[] brand_ids = request.getParameterValues("brand_id");
        int count=0;
        try (Connection conn= DBUtil.getConnection()) {
            //关闭自动提交
            conn.setAutoCommit(false);
            for (String brand_id : brand_ids) {
                count += brandService.delById(brand_id);
            }
            if (count!=brand_ids.length){
                //删除失败
                response.sendRedirect(request.getContextPath()+"/error.jsp");
            }
            //手动提交事务
            conn.commit();
            response.sendRedirect(request.getContextPath()+"/brand.jsp");
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                DBUtil.close(DBUtil.getConnection(),null,null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * chan
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doSelectByCategoryId(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String category_id = request.getParameter("category_id");
        List<Brand> brandList=brandService.selectByCategoryId(category_id);
        String s = JSON.toJSONString(brandList);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(s);
    }

    /*private void doShow(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Brand> brandList=brandService.selectAll();
        System.out.println(brandList);
        List<Category> categoryList=categoryService.selectAll();
        System.out.println(categoryList);
        //把查询到的集合存到session域
        HttpSession session = request.getSession();
        session.setAttribute("brandList",brandList);
        session.setAttribute("categoryList",categoryList);
        //跳转到展示页面jsp
        response.sendRedirect(request.getContextPath()+"/brand_manager.html");
    }*/
}
